package com.spider.gp.processor;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spider.gp.dao.GpSfJj;
import com.spider.gp.dao.GpSfJjDao;
import com.spider.gp.dao.ZhiShu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * description: 存文档
 *
 * @author clare
 * @date 2022/05/20 08:56
 **/
@Component
public class GpPrePriceProcessor implements PageProcessor {
    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000);

    @Autowired
    private GpSfJjDao gpSfJjDao;

    @Override
    public void process(Page page) {
        String s = page.getUrl().get();
        String reportTime = s.substring(s.length() - 8);
        String type = "";
        if (s.contains("lmt=3&")){
            type = "3";
        }
        if (s.contains("lmt=8&")){
            type = "8";
        }
        String code = page.getJson().jsonPath("$.data.code").get();
        String market = page.getJson().jsonPath("$.data.market").get();
        String name = page.getJson().jsonPath("$.data.name").get();
//        String preKPrice = page.getJson().jsonPath("$.data.preKPrice").get(); // 上一日价格

        List<String> all = page.getJson().jsonPath("$.data.klines").all(); //数据
        String curPriceJson = all.get(all.size() - 1); //获取最后一个
        String[] split = curPriceJson.split(",");
        String curPrice = split[2];

        AtomicReference<BigDecimal> total= new AtomicReference<>(new BigDecimal(0));

        all.forEach(m -> {
            //获取每天的价格
            String[] splitS = m.split(",");
            String curPriceS = splitS[2];
            BigDecimal c = new BigDecimal(curPriceS);
            total.set(total.get().add(c));
        });
        //11.89   11.74   12.00  11.72
//        System.out.println(total.get());
        BigDecimal divide = total.get().divide(new BigDecimal(all.size()) , 2   ,  BigDecimal.ROUND_HALF_UP);
        String preKPrice = divide.toPlainString();

        LambdaQueryWrapper<GpSfJj> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GpSfJj::getReportTime , reportTime);
        wrapper.eq(GpSfJj::getCode , code);
        wrapper.eq(GpSfJj::getDayType , type);
        gpSfJjDao.delete(wrapper);

        gpSfJjDao.insert(GpSfJj.builder().reportTime(reportTime).code(code).perPrice(preKPrice).name(name).dayType(type).curPrice(curPrice).build());

    }

    @Override
    public Site getSite() {
        return site;
    }
}








